<?php


namespace App\Http\Controllers;

use App\Exports\BookCatalog29;
use App\Exports\BookCatalog8;
use App\Exports\BookCatalog8JS;
use App\Exports\BookCatalogBZ29;
use App\Exports\BookCatalogLY;
use App\Exports\BookTitleExport29;
use App\Exports\BookTitleExport8;
use App\Exports\BookTitleExportLY;
use App\Models\DownloadJob;
use App\Models\PartCompany;
use App\Models\Project;
use App\Models\ProjectClassify;
use App\Services\BookCatalogService;
use App\Services\BookTitleService;
use App\Services\CommonService;
use App\Services\ExportService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Exceptions\ApiException;

/**
 * 导出案卷、卷内、备考表、封面、盒子脊背、卷内页码
 * Class ExportController
 * @package App\Http\Controllers
 */
class ExportController extends Controller
{
    public $exportService;
    public $bookTitleService;
    public $bookCatalogService;

    public function __construct(ExportService $exportService, BookTitleService $bookTitleService, BookCatalogService $bookCatalogService)
    {
        parent::__construct();
        $this->exportService      = $exportService;
        $this->bookTitleService   = $bookTitleService;
        $this->bookCatalogService = $bookCatalogService;
    }

    /**
     * 导出案卷目录
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2025-07-15 11:52
     */
    public function exportBookTitle(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $btSerialRange     = $request->input('bt_serial_range');
        $bookTitleIds      = to_array($request->input('ids'));
        if (empty($bookTitleIds)) { //如果没有勾选案卷，则使用范围
            $bookTitleIds = CommonService::getIdsBySerialRange($partCompanyId, $projectClassifyId, $btSerialRange);
        }
        $data = $this->exportService->exportBookTitle($partCompanyId, $projectClassifyId, $bookTitleIds);

        return $this->success($data);
    }

    /**
     * 导出卷内目录
     */
    public function exportBookCatalog(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $isHaveChildren    = $request->input('is_have_children', 0);
        $isZip             = $isHaveChildren; //因为只要有下级，就需要打包zip,所以他们的值其实一样
        $bookTitleIds      = to_array($request->input('ids'));
        $btSerialRange     = $request->input('bt_serial_range');
        if ($isHaveChildren) {
            $this->bookCatalogService->createUnitProZip($partCompanyId, $projectClassifyId);
        } else {
            if (empty($bookTitleIds)) { //如果没有勾选案卷，则使用范围
                $bookTitleIds = CommonService::getIdsBySerialRange($partCompanyId, $projectClassifyId, $btSerialRange);
                if (empty($bookTitleIds)) return $this->error('不存在这个序号区间的数据');
            }
            if (!BookCatalogService::checkIsNeedExport($partCompanyId, $projectClassifyId, '导出卷内目录', $bookTitleIds)) {
                $this->bookCatalogService->exportExcel($partCompanyId, $projectClassifyId, $bookTitleIds, null, $isZip, 1);
            }
        }
        return $this->success('', '已加入下载任务！');
    }

    /**
     * 导出全引目录
     */
    public function exportFullIndex(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $isHaveChildren    = $request->input('is_have_children', 0);
        $btSerialRange     = $request->input('bt_serial_range');
        $bookTitleIds      = to_array($request->input('ids'));
        $isZip             = $isHaveChildren; //因为只要有下级，就需要打包zip,所以他们的值其实一样
        if ($isHaveChildren) {
            $this->bookCatalogService->createUnitProZip($partCompanyId, $projectClassifyId, 2);
        } else {
            if (empty($bookTitleIds)) { //如果没有勾选案卷，则使用范围
                $bookTitleIds = CommonService::getIdsBySerialRange($partCompanyId, $projectClassifyId, $btSerialRange);
                if (empty($bookTitleIds)) return $this->error('不存在这个序号区间的数据');
            }
            if (!BookCatalogService::checkIsNeedExport($partCompanyId, $projectClassifyId, '导出全引目录', $bookTitleIds)) {
                $this->bookCatalogService->exportFullIndexExcel($partCompanyId, $projectClassifyId, $bookTitleIds, null, $isZip, 1);
            }
        }
        return $this->success('', '已加入下载任务！');
    }

    /**
     * 导出备考表
     */
    public function exportAppendix(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $btSerialRange     = request()->input('bt_serial_range');
        $bookTitleIds      = to_array($request->input('ids'));
        if (empty($bookTitleIds)) { //如果没有勾选案卷，则使用范围
            $bookTitleIds = CommonService::getIdsBySerialRange($partCompanyId, $projectClassifyId, $btSerialRange);
        }
        $data = $this->exportService->exportAppendix($partCompanyId, $projectClassifyId, $bookTitleIds);

        return $this->success($data);
    }

    /**
     * 导出封面
     */
    public function exportCover(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $btSerialRange     = request()->input('bt_serial_range');
        $bookTitleIds      = to_array($request->input('ids'));
        if (empty($bookTitleIds)) { //如果没有勾选案卷，则使用范围
            $bookTitleIds = CommonService::getIdsBySerialRange($partCompanyId, $projectClassifyId, $btSerialRange);
        }
        $data = $this->exportService->exportCover($partCompanyId, $projectClassifyId, $bookTitleIds); //生成word文件

        return $this->success($data);
    }

    /**
     * 导出盒子脊背
     */
    public function exportBox(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookTitleIds      = to_array($request->input('ids'));
        $btSerialRange     = request()->input('bt_serial_range');
        if (empty($bookTitleIds)) { //如果没有勾选案卷，则使用范围
            $bookTitleIds = CommonService::getIdsBySerialRange($partCompanyId, $projectClassifyId, $btSerialRange);
        }
        $data = $this->exportService->exportBox($partCompanyId, $projectClassifyId, $bookTitleIds); //生成word文件

        return $this->success($data);
    }

    /**
     * 导出卷内页码
     */
    public function exportPageNum(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $ids               = $request->input('ids');
        $catalogAtHead     = $request->input('catalog_at_head');
        $appendixAtEnd     = $request->input('appendix_at_end');
        $downloadUrl       = $this->bookCatalogService->exportPageNum($partCompanyId, $projectClassifyId, $ids, $catalogAtHead, $appendixAtEnd);

        CommonService::addProjectActionLog("导出卷内数据页码", 0, $partCompanyId, $projectClassifyId);

        $data = [
            'basename'     => pathinfo($downloadUrl)['basename'],
            'download_url' => $downloadUrl
        ];

        return $this->success($data);
    }

    /**
     * 在卷内导出卷内目录
     */
    public function exportBookCatalogInIt(Request $request)
    {
        $projectId         = $request->input('project_id');
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookTitleId       = $request->input('book_title_id');

        $dir = ExportService::getDir($partCompanyId, $projectClassifyId, [$bookTitleId], 2);
        $fileDir = "excels/{$dir}";
        CommonService::createDir($fileDir);
        $combinationId = Project::query()->where('id', $projectId)->value('combination_id');
        $filePath = "public/$fileDir/1.xlsx";
        if ($combinationId == 1) { //29号文
            (new BookCatalog29($partCompanyId, $projectClassifyId, $bookTitleId))->store($filePath);
        } elseif($combinationId == 2) { //8号文
            if (in_array($projectId, [5,15,16])) { //京石部分项目专用
                (new BookCatalog8JS($partCompanyId, $projectClassifyId, $bookTitleId))->store($filePath);
            } else { //普通8号文
                (new BookCatalog8($partCompanyId, $projectClassifyId, $bookTitleId))->store($filePath);
            }
        } elseif($combinationId == 3) { //兰渝
            (new BookCatalogLY($partCompanyId, $projectClassifyId, $bookTitleId))->store($filePath);
        } elseif ($combinationId == 4) { //标准29号文
            (new BookCatalogBZ29($partCompanyId, $projectClassifyId, $bookTitleId))->store($filePath);
        } else { //默认29号文
            (new BookCatalog29($partCompanyId, $projectClassifyId, $bookTitleId))->store($filePath);
        }
        sleep(1); //确保队列文件生成后在进行调格式
        $downloadUrl = ExportService::dealExcelByPython($projectId, $fileDir);
        $downloadUrl = config('site.domain') . $downloadUrl;
        $fileInfo    = pathinfo($downloadUrl);
        $data        = [
            'basename'     => $fileInfo['basename'],
            'download_url' => $downloadUrl
        ];

        return $this->success($data);
    }


}
